package org.example.java.nio.channels;

import java.io.Reader;
import java.io.Writer;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.CharBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Created by Juntao.Zhang on 2014/10/9.
 */
public class ServerSocketChannelTest {
  public static void main(String[] args) throws Exception {
    ServerSocketChannel serverSocket;
    SocketAddress bindPoint = new InetSocketAddress("localhost", 10000);

    serverSocket = ServerSocketChannel.open();
    serverSocket.socket().setReuseAddress(true);
    serverSocket.socket().bind(bindPoint);
    CharBuffer buffer = CharBuffer.allocate(20);
    SocketChannel socketChannel = serverSocket.accept();
    Reader reader = Channels.newReader(socketChannel, "utf-8");
    Writer writer = Channels.newWriter(socketChannel, "utf-8");
    while (true) {
      buffer.limit(20);
      buffer.position(0);
      int charsRead = reader.read(buffer);
      buffer.flip();
      System.out.printf("Chars read = %s  %s%n", charsRead, buffer.toString());
      writer.write("@^@\n");
      writer.flush();
    }

  }


}
